using FeishuWorkflowService.Models;
using FeishuWorkflowService.Services;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;
using Serilog;
using Serilog.Events;

var builder = WebApplication.CreateBuilder(args);

// 1. 配置 Serilog
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Information() // 最小日志级别
    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) // 覆盖Microsoft命名空间的日志级别
    .MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
    .Enrich.FromLogContext() // 从日志上下文丰富日志信息
    // 2. 配置日志输出
    .WriteTo.Console() // 输出到控制台
    .WriteTo.File(
        path: "logs/log-.txt", // 日志文件路径
        rollingInterval: RollingInterval.Day, // 按天滚动
        retainedFileCountLimit: 7, // 保留7天日志
        outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}" // 日志格式
    )
    .CreateLogger();

// 3. 替换默认日志为Serilog
builder.Host.UseSerilog();

builder.Services.Configure<FeishuConfig>(
    builder.Configuration.GetSection(FeishuConfig.SectionName) // 使用常量避免硬编码
);

builder.Services.AddAutoMapper(typeof(Program)); // 传入任意包含映射配置的程序集类型

// Add services to the container.
builder.Services.AddControllers().AddNewtonsoftJson();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// 注册自定义服务
builder.Services.AddHttpClient();
builder.Services.AddSingleton<IFeishuService, FeishuService>();
builder.Services.AddSingleton<IWorkflowService, WorkflowService>();
// 注册内存监控后台服务
builder.Services.AddHostedService<MemoryMonitorService>();
// 允许通过依赖注入获取MemoryMonitorService实例
builder.Services.AddSingleton<MemoryMonitorService>();

var app = builder.Build();

// 调试日志路径
var logPath = Path.Combine(app.Environment.ContentRootPath, "logs");
Log.Information("日志文件夹路径: {LogPath}", logPath);

// 确保日志文件夹存在
if (!Directory.Exists(logPath))
{
    Directory.CreateDirectory(logPath);
}

// 配置静态文件
app.UseStaticFiles();

// 配置MIME类型和编码
var contentTypeProvider = new FileExtensionContentTypeProvider();
contentTypeProvider.Mappings[".log"] = "text/plain; charset=utf-8"; // 指定UTF-8编码
contentTypeProvider.Mappings[".txt"] = "text/plain; charset=utf-8";

// 配置logs文件夹访问
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(logPath),
    RequestPath = "/logs",
    ServeUnknownFileTypes = false,
    ContentTypeProvider = contentTypeProvider,
    OnPrepareResponse = ctx =>
    {
        // 关键：在响应头中明确指定编码为UTF-8
        ctx.Context.Response.Headers["Content-Type"] = "text/plain; charset=utf-8";

        // 开发环境配置
        if (app.Environment.IsDevelopment())
        {
            ctx.Context.Response.Headers["Access-Control-Allow-Origin"] = "*";
        }
    }
});

// 开发环境启用目录浏览

app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
    FileProvider = new PhysicalFileProvider(logPath),
    RequestPath = "/logs"
});



app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();